package cn.hdu.liang.ch02;

import cn.hdu.liang.ch02.classpath.ClassPath;

import java.util.Scanner;

public class Main {

    // java -Xjre /usr/lib/jvm/default-java/jre java.lang.Object
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String argsLine = sc.nextLine();
        Cmd cmd = new Cmd(argsLine);

        if(!cmd.isRightFmt) {
            cmd.printUsage();
        } else {
            if(cmd.versionFlag) {
                System.out.println("java version \"1.8.0_144\"\n" +
                        "Java(TM) SE Runtime Environment (build 1.8.0_144-b01)\n" +
                        "Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)");
            } else if(cmd.helpFlag || cmd.args == null) {
                cmd.printUsage();
            } else {
                startJVM(cmd);
            }
        }
    }

    private static void startJVM(Cmd cmd) {

        System.out.println("classpath: " + cmd.cpOption);
        System.out.println("class: " + cmd.clazz);
        System.out.print("方法的参数 args:");
        for(int i = 0; i < cmd.args.length; i++) {
            System.out.print(cmd.args[i] + " ");
        }
        System.out.println();

        String className = cmd.clazz.replace(".", "/");
        System.out.println("className: " + className);

        ClassPath cp = new ClassPath(cmd.XjreOption, cmd.cpOption);
        byte[] data = cp.readClass(className);
        System.out.println(byteToHex(data));
    }

    /**
     * byte转十六进制，输出看起来方便些
     */
    private static String byteToHex(byte[] bytes) {
        if(bytes == null || bytes.length <= 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder("");
        for(byte b : bytes) {
            String hv = Integer.toHexString(b & 0xFF).toUpperCase();
            if(hv.length() < 2) {
                sb.append(0);
            }
            sb.append(hv).append(" ");
        }
        return sb.toString();
    }
}
